package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result sendCode(String phone) {
        //1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            //直接返回错误
            return Result.fail("手机号格式有误");
        }
        //2.符合，生成验证码
        String code = RandomUtil.randomNumbers(6);
        log.info("发送验证码,{}",code);
       /* //3.保存验证码到session
        session.setAttribute("code", code);*/

        //3.保存验证码到redis
        stringRedisTemplate.opsForValue().set("login:code",code,5, TimeUnit.MINUTES);
        //4.返回结果
        return Result.ok(code);
    }



    @Override
    public Result login(LoginFormDTO loginForm) {
        //1.校验手机号
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)) {
            //不符合直接返回错误
            return Result.fail("手机号格式有误");
        }
        //2.校验验证码
        String code = loginForm.getCode();
        /*String sessionCode = (String) session.getAttribute("code");*/
        String code1= stringRedisTemplate.opsForValue().get("login:code");
        if (code1==null || !code1.equals(code)) {
            return Result.fail("验证码错误");
        }
        //3.查询用户
        User user = query().eq("phone", phone).one();
        if(user==null){
           user = createNewUser(phone);
            save(user);
        }
        //4.保存用户到redis
       /* session.setAttribute("user", user);*/
        //4.1随机token
        String token = UUID.randomUUID(true).toString();
        //4.2将对象转化为hash存储
        UserDTO userDTO=new UserDTO();
        BeanUtils.copyProperties(user,userDTO);

        //dto多个字段用map方便
        Map<String, Object> map = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((name, value) -> value.toString()));
        stringRedisTemplate.opsForHash().putAll(RedisConstants.LOGIN_USER_KEY+token,map);
        stringRedisTemplate.expire(RedisConstants.LOGIN_USER_KEY,5,TimeUnit.MINUTES);
        //4,3返回token
        return Result.ok(token);
    }





    private User createNewUser(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(SystemConstants.USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        return user;
    }
}
